package com.hyq.gateway.filter;

import com.hyq.gateway.entity.BeSubscriber;
import com.hyq.gateway.enums.ResultEnum;
import com.hyq.gateway.mapper.BeSubscriberMapper;
import com.hyq.gateway.utils.JsonUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private BeSubscriberMapper beSubscriberMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String token = ctx.getRequest().getHeader("access-token");
        if (!checkSubscriber(token) || token == null) {
            ctx.getResponse().setContentType("text/json;charset=UTF-8");
            Map<String, Object> response = new HashMap<>();
            response.put("code", ResultEnum.UNAUTHORIZED.getCode());
            response.put("msg", ResultEnum.UNAUTHORIZED.getMsg());
            String body = JsonUtil.toJson(response);
            ctx.setResponseBody(body);
            ctx.setSendZuulResponse(false);
            return null;
        }
        return null;
    }

    private Boolean checkSubscriber(String token) {
        Object subscriber = redisTemplate.opsForValue().get("subscriber" + token);
        if (subscriber == null) {
            BeSubscriber beSubscriber = new BeSubscriber();
            beSubscriber.setToken(token);
            beSubscriber = beSubscriberMapper.selectOne(beSubscriber);
            if (beSubscriber == null) {
                return false;
            }
            redisTemplate.opsForValue().set("subscriber" + token, beSubscriber);
        }
        return true;

    }
}
